import { history } from 'umi';
import { message } from 'antd';
import api from '../../services';

const { loginUser, loginAdmin,addUser } = api

export default {
  namespace: 'login',
  state: { errorMsg: { message: null, timeStamp: 0 } },
  effects: {
    *loginUser({ payload, callback }, { put, call, select }) {
      const data = yield call(payload.userType === 0 ? loginAdmin : loginUser, payload);
      if (data.code === 1) {
        yield put({ type: "errorHandle", payload: data.message })
      }
      else {
        yield put({
          type: "user/updateUser",
          payload: {
            userInfo: {...data.data},
            accessToken: data.accessToken,
            refreshToken: data.refreshToken
          }
        });
        message.success("登录成功！", 1);
      }
    },
    *addUser({ payload }, { put, call, select }) {
      const result = yield call(addUser, payload);
      if (result.code === 0) {
          yield put({ type: "queryUser" });
          message.success("添加成功");
      }
      else {
          message.error(result.message, 2);
      }
  },
  },
  reducers: {
    errorHandle(_, { payload: message }) {
      return { errorMsg: { message, timeStamp: Date.now() } }
    }
  }
};